package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.constant.CutPointExpressionConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import com.sky.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @author 唐佳辉
 */
//切面注解
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    //定义切面方法
    @Before(CutPointExpressionConstant.PUBLIC_FIELD)
    public void autoFillInsert(JoinPoint joinPoint) {
        log.info("公共字段自动填充方法");
        //获取方法签名 获取方法上自定义注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = annotation.value();
        log.info("SQL操作类型:{}", operationType);
        Object[] args = joinPoint.getArgs();

        if (args == null || args.length == 0) {
            return;
        }
        Object arg = args[0];

        if (operationType == OperationType.INSERT) {
            try {
                Method setCreateTime = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateTime = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setCreateTime.invoke(arg, LocalDateTime.now());
                setCreateUser.invoke(arg, BaseContext.getCurrentId());
                setUpdateTime.invoke(arg, LocalDateTime.now());
                setUpdateUser.invoke(arg, BaseContext.getCurrentId());
            } catch (Exception e) {
                throw new BaseException("执行插入操作时公共字段自动填充异常");
            }

        } else if (operationType == OperationType.UPDATE) {
            try {
                Method setUpdateTime = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(arg, LocalDateTime.now());
                setUpdateUser.invoke(arg, BaseContext.getCurrentId());
            } catch (Exception e) {
                throw new BaseException("执行跟新操作时公共字段自动填充异常");
            }
        }


    }


    /**
     * 定义公共字段自动填充切入点
     */
   /* @Pointcut(INSERT)
    public void insertPointCut() {
    }*/

    /**
     * 定义公共字段自动填充切入点
     */
 /*   @Before("insertPointCut()")
    public void updatePointCut() {
    }*/

}
